package com.jingge.autojob.skeleton.cluster.balancing;

import com.jingge.autojob.skeleton.cluster.model.ClusterNode;
import com.jingge.autojob.skeleton.framework.task.AutoJobTask;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 负载均衡策略上下文
 *
 * @author JingGe(* ^ ▽ ^ *)
 * @date 2023-09-19 14:04
 * @email 1158055613@qq.com
 */
public class LoadBalancingStrategyContext {
    private final LoadBalancingStrategy strategy;
    private static final AtomicInteger defaultPos = new AtomicInteger(-1);

    public LoadBalancingStrategyContext(LoadBalancingStrategy strategy) {
        if (strategy == null) {
            throw new IllegalArgumentException("负载均衡策略不得为空");
        }
        this.strategy = strategy;
    }

    public ClusterNode choose(List<ClusterNode> solves, AutoJobTask task) {
        try {
            if (solves == null || solves.size() == 0) {
                return null;
            }
            strategy.beforeChoose(solves);
            ClusterNode chosen = strategy.choose(solves, task);
            strategy.afterChoose(chosen, solves);
            return chosen;
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (defaultPos.incrementAndGet() >= solves.size()) {
            defaultPos.set(0);
        }
        return solves.size() > 0 ? solves.get(defaultPos.get()) : null;
    }
}
